<template>
  <div>
    <el-form ref="editForm" :model="editForm" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="选择委托单位" prop="customerId">
            <el-select
              v-model="editForm.customerId"
              placeholder="选择委托单位"
              filterable
              @change="getBuilds"
            >
              <el-option
                v-for="i in userList"
                :key="i.userId"
                :label="i.nickName"
                :value="i.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择楼栋" prop="buildingId">
            <el-select v-model="editForm.buildingId" placeholder="选择楼栋" filterable>
              <el-option
                v-for="i in buildList"
                :key="i.id"
                :label="i.name"
                :value="i.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="文件上传" prop="files">
            <!-- accept=".rar,.zip,.doc,.docx,.pdf" -->
            <el-upload
              ref="uploadFile"
              :action="uploadUrl"
              :limit="10"
              multiple
              accept=".pdf"
              :before-remove="beforeRemove"
              :file-list="uploadList"
              :on-success="handleFileSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">上传文件</el-button>
              <div slot="tip" class="el-upload__tip">支持格式：PDF</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div style="display: flex; justify-content: center; margin-top: 1rem">
            <el-button type="primary" style="margin-top: 12px" @click="handleNext">
              暂存并下一步
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="tips-content">
      <i class="el-icon-warning-outline" />
      <div>
        <div style="font-size: 16px; font-weight: bold">上传注意事项：</div>
        <div>1、若消防图纸pdf文件中有楼层标识，则直接略过以下规则直接上传图纸！</div>
        <div>
          2、若消防图纸PDF文件中没有楼层标识，您需对PDF文件名进行重命名再上传识别（若已按以下规则命名则不需要重命名）。
        </div>
        <div style="padding-left: 22px">文件名包含以下规则：</div>
        <div style="padding-left: 52px">
          1.单楼层 X楼 或 X层 （例：成飞公园项目1楼平面图）
        </div>
        <div style="padding-left: 52px">
          2.多楼层 X-Y楼 或 X-Y层（例：成飞公园项目 1-20楼平立图）
        </div>
        <div style="padding-left: 52px">
          3.地下室 地下X楼 或地下X层 （例：成飞公园项目 地下1楼）
        </div>
        <div>3、1个PDF只能包含一张图纸 如有多张图纸请拆分保存为单张PDF</div>
      </div>
    </div>
  </div>
</template>
<script>
import { postAiPredict } from "@/api/system/ai";
import { getUserList, getBuildList } from "@/api/contract/contractOrg";
export default {
  data() {
    return {
      editForm: {
        customerId: null, // 委托单位id
        buildingId: null, // 建筑id
        buildingName: null, // 建筑名称
        files: [], // 附件地址
      },
      // 表单校验
      rules: {
        customerId: [{ required: true, message: "委托单位不能为空", trigger: "blur" }],
        buildingId: [{ required: true, message: "建筑不能为空", trigger: "blur" }],
        files: [{ required: true, message: "文件不能为空", trigger: "blur" }],
      },
      userList: [], // 委托单位列表
      buildList: [], // 建筑列表
      uploadList: [],
      // 上传参数
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
    };
  },
  methods: {
    // 初始化
    init(reset = false) {
      this.getUsers();
      if (reset) {
        this.resetForm("editForm");
        this.uploadList = [];
        this.$refs.uploadFile.clearFiles();
      }
    },
    // 获取委托单位列表
    getUsers() {
      getUserList("02").then((res) => {
        this.userList = res.data;
      });
    },
    // 获取建筑列表
    getBuilds() {
      this.editForm.buildingId = null;
      getBuildList({ customerId: this.editForm.customerId }).then((res) => {
        this.buildList = res.rows;
      });
    },
    // 下一步
    handleNext() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.$emit("refresh", { step: 4, num: this.editForm.files.length });
          postAiPredict(this.editForm)
            .then((res) => {
              if (res.code == 200) {
                this.editForm.buildingName = this.buildList.find(
                  (i) => i.id == this.editForm.buildingId
                ).name;
                this.$cache.local.setJSON("ai-predict", {
                  step: 2,
                  form: this.editForm,
                  rows: res.rows,
                  total: res.total,
                });
                this.$emit("refresh", {
                  step: 2,
                  form: this.editForm,
                  rows: res.rows,
                  total: res.total,
                });
              }
            })
            .catch(() => {
              this.$emit("refresh", {
                step: 1,
              });
            });
        }
      });
    },
    // 移除上传
    beforeRemove(file, files) {
      this.uploadList = files;
      this.editForm.files = files
        .filter((i) => i.status == "success")
        .map((i) => {
          return {
            url: i.response.url,
            fileName: i.name,
            fileSize: i.size / 1024 / 1024,
          };
        });
    },
    // 文件上传成功处理
    handleFileSuccess(res, file, files) {
      console.log(files);
      this.uploadList = files;
      this.editForm.files = files
        .filter((i) => i.status == "success")
        .map((i) => {
          return {
            url: i.response.url,
            fileName: i.name,
            fileSize: i.size / 1024 / 1024,
          };
        });
    },
    // 文件上传前的大小
    beforeAvatarUpload(file) {
      // const typeList = [".rar", ".zip", ".doc", ".docx", ".pdf"];
      const typeList = [".pdf"];
      const lastIndex = file.name.lastIndexOf(".");
      if (lastIndex > -1) {
        const fileType = file.name.substring(lastIndex).toLowerCase();
        if (typeList.includes(fileType)) {
          if (file.size / 1024 / 1024 > 1024) {
            this.$message.error("文件大小不能超过1GB");
            return false;
          } else {
            return true;
          }
        } else {
          this.$message.error("请上传正确的文件格式");
          return false;
        }
      } else {
        return false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.tips-content {
  background-color: #ffeee6;
  border-radius: 4px;
  border: 1px solid #479fc6;
  padding: 20px;
  margin-top: 50px;
  display: flex;
  i {
    font-size: 30px;
    margin-right: 20px;
    color: #ff931e;
    font-weight: bold;
  }
  > div {
    flex: 1;
    font-size: 14px;
    color: #000;
    line-height: 24px;
  }
}
</style>
